import { defineStore } from "pinia";
import { requestInstance } from "~service/request";

export interface DistrictSelectChild {
	children?: DistrictSelectChild[];
	districtCode: string;
	districtName: string;
	parentDistrictCode?: string;
}

export const useDistrict = defineStore<
	"userDistrictList",
	{
		districtList: DistrictSelectChild[];
		idMapToDistrict: Record<string, DistrictSelectChild>;
	},
	any,
	{
		initialize: () => Promise<void>;
		getChildFromIds: (paths: string[]) => DistrictSelectChild;
	}
>("userDistrictList", {
	state: () => ({ districtList: [], idMapToDistrict: {} }),
	persist: {
		enabled: true,
		strategies: [
			{
				key: "userDistrictList.districtList",
			},
		],
	},
	actions: {
		initialize() {
			if (this.districtList.length > 0) {
				return Promise.resolve();
			}
			return requestInstance
				.get<any, ServiceStructure>(
					"/trade/view/preApply/preAnnouncement/districtList"
				)
				.then((rs) => {
					if (rs.ok) {
						const list = [
							{
								districtCode: null,
								districtName: "不限",
								children: [],
							},
							...rs.data[0].children,
						];

						const nextMaps = {};

						const stack = [...list] as DistrictSelectChild[];

						while (stack.length > 0) {
							const item = stack.shift();
							nextMaps[item.districtCode] = {
								districtName: item.districtName,
								districtCode: item.districtCode,
							};

							if (Array.isArray(item.children)) {
								stack.push(...item.children);
							}
						}

						this.idMapToDistrict = nextMaps;
						this.districtList = list;
					}
				});

			// return userService.getDistrictList<ServiceStructure<any[]>>().then(rs => {
			//   if (rs.ok) {
			//     this.districtList = rs.data;
			//   }
			// });
		},

		/**
		 * 注意，引用类型会被改变
		 * @param paths is list
		 * @returns DistrictSelectChild
		 */
		getChildFromIds(paths: string[]): DistrictSelectChild {
			const list = this.districtList;

			const pathStack = paths;

			let ans = null;
			const stack = [list];

			while (stack.length > 0) {
				const currentId = pathStack.shift();
				const currentList = stack.pop() as DistrictSelectChild[];

				ans = currentList?.find(el => el.districtCode === currentId);

				if (pathStack.length === 0 || typeof ans === "undefined") {
					break;
				}

				stack.push(ans.children);
			}

			return ans;
		},
	},
});
